package com.woniu.factorys;


import com.woniu.entity.Person;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @author WenXin
 * @version 1.0
 * @description: TODO
 * @date 2022/8/17 19:21
 */
public class MyBeanFactory {
    //创建一个map,来存储配置文件中的key跟value
    private static Map<String, String> map = new HashMap<>();

    private static Person person;

    static {
        //创建配置文件对象，读取配置文件的所有内容
        Properties properties = new Properties();
        try {
            //加载文件到配置文件对象中
            properties.load(MyBeanFactory.class.getResourceAsStream("../test/person.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Set<String> keys = properties.stringPropertyNames();
        for (String key : keys) {
            //遍历一次，获取一次配置文件的实体类全路径（全限定类名），并存到map中
            String url = properties.getProperty(key);
            map.put(key, url);
        }
    }

    /* prototype原型对象的获取方法
     * @Author: WenXin
     * @Datetime: 2022/8/17 19:31
     * @Params:
     * @Return:
     **/
    public static Object getBeanPro(String name) {
        String url = map.get(name);

        try {
            return Class.forName(url).newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /* 获取singleton单例的对象
     * @Author: WenXin
     * @Datetime: 2022/8/17 19:37
     * @Params:
     * @Return:
     **/
    public static synchronized Object getBeanSin(String name) {
        //获取对应key的全限定类名
        String url = map.get(name);
        try {
            if (person == null) {
                person = (Person) Class.forName(url).newInstance();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return person;
    }
}
